﻿using IdentityModel;
using IdentityModel.Client;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Models.Identity;
using Models.JsonResultModel;
using System.Net.Http.Headers;
using System.Security.Principal;
using UtilsORM.MySqlData;
using ServiceWeb.DBGateway;
using UtilsBase;
using UtilsORM;
using UtilsORM.MySqlData;
using GatewayServer.Controllers.API.Common;

namespace GatewayServer.Controllers.API.Mobile
{
    [Route("api/mobile/[controller]/[action]")]
    [ApiController]
    // [BasicAuthentication]
    public class PlainItemController : ApiCommonControllerBase
    {
       
        public RespResultData setPlainItemValue(string pguid, string modelno, string val)
        {

            new DBIotDeviceTaskPlainItem().setPlainItemValue(pguid, int.Parse(modelno), val);
            return RespResult.Sucess();
        }
       
        public RespResultData getPlainItemList(string tpguid)
        {
            return RespResult.Sucess(new DBIotDeviceTaskPlainItem().getPlainItemListTable(tpguid));
        }
       
        public RespResultData getPlainItem(string tpiguid)
        {
            return RespResult.Sucess(new DBIotDeviceTaskPlainItem().getPlainItemTable(tpiguid));
        }
       
        public RespResultData delPlainItem(string tpiguid)
        {
            new DBIotDeviceTaskPlainItem().delItem(tpiguid);
            return RespResult.Sucess();
        }

        EFYihongIotContext ef = new EFYihongIotContext();
       
        public RespResultData savePlanItem(string order, string tpguid, string tpiguid, string dguid, string dcguid, string second)
        {
            iot_device_task_plain_item item = new iot_device_task_plain_item();

            iot_device device = ef.iot_device.Where(c => c.d_guid == dguid).FirstOrDefault();
            iot_device_command command = new DBIotDeviceCommand().getCommand(dcguid);


            if (order == "add")
            {
                item.tpi_tp_guid = tpguid;
                item.tpi_guid = Guid.NewGuid().ToString();
            }
            else
            {
                item = ef.iot_device_task_plain_item.Where(c => c.tpi_guid == tpiguid).FirstOrDefault();
                item.tpi_guid = tpiguid;
            }
            item.tpi_taskobj_guid = dguid;
            item.tpi_key = command.dc_key;
            if (item.tpi_key == "delay")
            {
                item.tpi_value = second;
                item.tpi_type = 0;
            }
            else
            {
                item.tpi_type = 0;
            }

            item.tpi_title = device.d_name + command.dc_name;

            new DBIotDeviceTaskPlainItem().saveAll(item);
            return RespResult.Sucess();
        }

    }
}
